package cerebrum.controller.screen;

import cerebrum.common.CommonConst;
import cerebrum.common.EmptyChecker;
import cerebrum.common.FileUtil;
import cerebrum.common.LunarUtil;
import cerebrum.crawler.VerseWebCrawler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.concurrent.Task;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;

public class VerseUtil {
    private VerseUtil() {

    }

    private static List<List<String>> list = new ArrayList<>();
    private static Random random;

    static {
        try {
            random = SecureRandom.getInstanceStrong();
            //开启后台加载
            new Thread(new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    downloadVerse(true);
                    return null;
                }

            }).start();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static List<String> nextVerse() {
        if (EmptyChecker.isEmpty(list)) {//如果初始化未能加载爬取的诗句，则加载默认的诗句
            JSONObject jsonObject = FileUtil.readDefault();
            list.addAll((Collection<? extends List<String>>) jsonObject.get("verseDefault"));
            //开启后台加载
            new Thread(new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    downloadVerse(false);//再次尝试加载
                    return null;
                }

            }).start();
        }
        return list.get(random.nextInt(list.size()));
    }


    public static boolean isVerse() {
        Set<String> keys = VerseConfigPropertiesUtil.getKeys();
        return EmptyChecker.isEmpty(keys);
    }

    public static void downloadVerse(boolean isInit) {
        try {
            HashMap<String, Object> today = LunarUtil.today();
            //节气
            String solarTerm = String.valueOf(today.get("solarTerm")).replace("节", "");
            //节日
            String lunarHoliday = String.valueOf(today.get("lunarHoliday")).replace("节", "");//传统节日
            //不是初始化，那就说明第一次静态加载的时候因为某种原因下载未能成功，尝试再次加载直接默认类型
            if (!isInit) {
                defaultVerse();
            } else {
                if (EmptyChecker.notEmpty(solarTerm)) {
                    list.addAll(VerseWebCrawler.getVerseMsgs(solarTerm));
                } else if (EmptyChecker.notEmpty(lunarHoliday)) {
                    list.addAll(VerseWebCrawler.getVerseMsgs(solarTerm));
                } else if (isVerse()) {
                    defaultVerse();
                } else {
                    for (int i = 0; i < CommonConst.VERSE_TYPE_CURRENCY.length; i++) {
                        try {
                            list.addAll((Collection<? extends List<String>>) JSON.parse(VerseConfigPropertiesUtil.get(CommonConst.VERSE_TYPE_CURRENCY[i])));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 爬取默认的集中类型的诗句，在默认
     */
    private static void defaultVerse() {
        String[] str = CommonConst.VERSE_TYPE_CURRENCY;

        for (int i = 0; i < str.length; i++) {
            List<List<String>> verseMsgs = VerseWebCrawler.getVerseMsgs(str[i]);
            list.addAll(verseMsgs);
            VerseConfigPropertiesUtil.set(str[i], JSON.toJSONString(verseMsgs));
        }
    }

}
